package com.leo;

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Paint;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ScreenshotDemo extends Application {

    private ImageView imageView;
    private Stage primary;
    private Stage stage;

    private double begin_x;
    private double begin_y;

    private double end_x;
    private double end_y;

    private HBox hBox;
    private Label label;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        primary = primaryStage;
        AnchorPane root = new AnchorPane();

        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.setWidth(1000);
        primaryStage.setHeight(600);
        primaryStage.centerOnScreen();
        primaryStage.setTitle("系统托盘");
        primaryStage.show();

        Button button = new Button("截图");

        imageView = new ImageView();
        imageView.setFitWidth(400d);
        imageView.setPreserveRatio(true);

        root.getChildren().addAll(button, imageView);
        AnchorPane.setTopAnchor(button, 20d);
        AnchorPane.setLeftAnchor(button, 50d);
        AnchorPane.setTopAnchor(imageView, 50d);
        AnchorPane.setLeftAnchor(imageView, 25d);

        button.setOnAction(event -> {
            show();
        });

        // 快捷键
        KeyCombination key = KeyCombination.valueOf("ctrl+alt+p");
        Mnemonic mn = new Mnemonic(button, key);
        scene.addMnemonic(mn);
    }

    public void show() {
        // 最小化
        primary.setIconified(true);

        // 弹框
        AnchorPane an = new AnchorPane();
        an.setOpacity(0.1);
        Scene scene = new Scene(an);
        scene.setFill(Paint.valueOf("#ffffff00"));
        stage = new Stage();
        // 透明模式
        stage.initStyle(StageStyle.TRANSPARENT);
        stage.setFullScreenExitHint("");
        stage.setScene(scene);
        stage.setFullScreen(true);
        stage.show();
        drag(an);

        scene.setOnKeyPressed(event -> {
            if (event.getCode() == KeyCode.ESCAPE) {
                stage.close();
                primary.setIconified(false);
            }
        });
    }

    public void drag(AnchorPane an) {
        an.setOnMousePressed(event -> {
            if (event.getButton() == MouseButton.PRIMARY) {
                an.getChildren().clear();

                label = new Label();
                label.setAlignment(Pos.CENTER);
                label.setPrefHeight(30);

                hBox = new HBox();
                hBox.setBackground(null);
                hBox.setBorder(new Border(new BorderStroke(Paint.valueOf("#CD3700"), BorderStrokeStyle.SOLID, null, new BorderWidths(2))));

                // 获取按下时区域坐标
                begin_x = event.getSceneX();
                begin_y = event.getSceneY();

                an.getChildren().addAll(hBox, label);
                AnchorPane.setTopAnchor(hBox, begin_y);
                AnchorPane.setLeftAnchor(hBox, begin_x);
                if (begin_y <= label.getPrefHeight()) {
                    AnchorPane.setTopAnchor(label, begin_y);
                } else {
                    AnchorPane.setTopAnchor(label, begin_y - label.getPrefHeight());
                }
                AnchorPane.setLeftAnchor(label, begin_x);
            }
        });

        an.setOnMouseReleased(event -> {
            if (event.getButton() == MouseButton.PRIMARY) {
                // 释放时的坐标
                end_x = event.getSceneX();
                end_y = event.getSceneY();

                HBox hBox = new HBox(10);
                hBox.setPrefWidth(92);
                hBox.setPrefHeight(30);
                Button button = new Button("截图");
                Button cancel = new Button("取消");
                hBox.getChildren().addAll(button, cancel);

                an.getChildren().add(hBox);
                if (end_y >= an.getHeight() - hBox.getPrefHeight() || (end_y < begin_y && end_y > hBox.getPrefHeight())) {
                    AnchorPane.setTopAnchor(hBox, end_y - hBox.getPrefHeight());
                } else {
                    AnchorPane.setTopAnchor(hBox, end_y + 2);
                }

                if (end_x > begin_x) {
                    AnchorPane.setLeftAnchor(hBox, end_x - hBox.getPrefWidth());
                } else {
                    AnchorPane.setLeftAnchor(hBox, end_x + 2);
                }

                cancel.setOnAction(event1 -> {
                    an.getChildren().clear();
                });

                button.setOnAction(event1 -> {
                    try {
                        getScreenImg();
                    } catch (AWTException | IOException e) {
                        e.printStackTrace();
                    }
                });
            } else {
                stage.close();
                primary.setIconified(false);
            }
        });

        // 拖拽
        // 启动拖拽监听
        an.setOnDragDetected(event -> {
            if (event.getButton() == MouseButton.PRIMARY) {
                an.startFullDrag();
            }
        });
        // 在什么上边拖拽
        an.setOnMouseDragOver(event -> {
            if (event.getButton() == MouseButton.PRIMARY) {
                double x = event.getSceneX();
                double y = event.getSceneY();

                double width = 0;
                double height = 0;

                if (x > begin_x) {
                    width = x - begin_x;
                } else {
                    width = begin_x - x;
                    hBox.setTranslateX(-width);
                }
                hBox.setPrefWidth(width);

                if (y > begin_y) {
                    height = y - begin_y;
                } else {
                    height = begin_y - y;
                    hBox.setTranslateY(-height);
                }
                hBox.setPrefHeight(height);

                label.setText(width + " * " + height);
            }
        });
    }

    public void getScreenImg() throws AWTException, IOException {
        // 关闭半透明页面
        stage.close();

        double w = end_x - begin_x;
        double h = end_y - begin_y;

        // awt截图功能
        Rectangle rec = new Rectangle((int) begin_x, (int) begin_y, (int) w, (int) h);
        if (w < 0 && h < 0) {
            rec = new Rectangle((int) end_x, (int) end_y, (int) -w, (int) -h);
        }

        if (h < 0 && w >= 0) {
            rec = new Rectangle((int) begin_x, (int) end_y, (int) w, (int) -h);
        }

        if (h >= 0 && w < 0) {
            rec = new Rectangle((int) end_x, (int) end_y, (int) -w, (int) h);
        }

        Robot robot = new Robot();
        BufferedImage screenCapture = robot.createScreenCapture(rec);
        // 转换成 javafx
        WritableImage wi = SwingFXUtils.toFXImage(screenCapture, null);
        imageView.setImage(wi);

        // 放入剪切板
        Clipboard clipboard = Clipboard.getSystemClipboard();
        ClipboardContent content = new ClipboardContent();
        content.putImage(wi);
        clipboard.setContent(content);

        // 存入电脑硬盘中
        ImageIO.write(screenCapture, "png", new File("D:\\log\\1.png"));

        // 恢复原屏幕
        primary.setIconified(false);
    }
}
